package com.baturu.vin.hyundai.transformer;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author: chenjiahao
 * @Time: 2019/4/4
 */
@Slf4j
public class ListMapTransformers {

    /**
     * 将sql结果（List<Map<String,String>>）转化成对应的List<T>
     *
     * @param input  sql返回的结果
     * @param claszz 转化的对象DTO,需要持有无参构造方法
     * @param <T>    泛型
     * @return list
     */
    public static <T> List<T> mapConvertToBean(List<Map<String, String>> input, Class<T> claszz) {
        List<T> result = Lists.newArrayList();
        try {
            for (Map<String, String> dto : input) {
                BeanInfo beanInfo = Introspector.getBeanInfo(claszz);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (ArrayUtils.isEmpty(propertyDescriptors)) {
                    log.warn("{}包含的属性为空", claszz.getSimpleName());
                    return null;
                }
                T v = claszz.newInstance();
                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    String name = propertyDescriptor.getName();
                    if ("class".equals(name)) {
                        continue;
                    }
                    propertyDescriptor.getWriteMethod().invoke(v, dto.getOrDefault(propertyDescriptor.getName(), ""));
                }
                result.add(v);
            }
        } catch (Exception e) {
            log.error("List<Map<String,String>>转换List<{}>失败，原因:{}", claszz.getSimpleName(), e);
            return Collections.emptyList();
        }
        return result;
    }
}
